<template>
	<div class="comment" id="rightContentScroll">
		<div class="workSheetCommentBox">
			<div v-if="ulList.length === 0" style="display:flex;align-items: center;justify-content: center;text-align:center;margin-top: 5%">
				<div>
					<img src="../../../../assets/img/slaEmpty.png" alt="">
					<div class="empty-text">暂无内容</div>
				</div>
			</div>
			<div v-else class="chat-log">
				<div class="activity-panel">
					<ul class="activities-list" v-for="(item, index) in ulList" :key="index">
						<boardItem :userObj="userObj" :item="item">
							<template>
								<uploadList :list="item.attach" :isHiddenDelBtn="true"></uploadList>
							</template>
						</boardItem>
					</ul>
					<div class="more-btn" @click.stop="getScrollFetchData" v-if="totalPage !== page.pageNumber && totalPage">加载更多</div>
				</div>
			</div>
			<div class="send-div">
				<div class="activity-creator-wrap">
					<div class="comment-box-wrap">
						<div class="comment-box-input-wrap">
							<el-input class="flex-text-wrap" type="textarea" :autosize="{ minRows: 2}" placeholder="请输入内容" :maxlength="500" v-model="inputVal">
							</el-input>
						</div>
						<uploadList :list="this.fileList" @remove="remove" style="margin-top: 16px" :progress="progress"></uploadList>
					</div>
					<div class="oper-btn">
            <el-upload ref="upload" action="" :before-upload="beforeUpload" :on-error="uploadError" :http-request="uploadRequest" v-bind="$attrs" :on-success="handleSuccess" :show-file-list="false" :on-progress="onFileProgress" multiple>
              <div class="upload--text">
                上传本地文件
              </div>
            </el-upload>
						<el-button size="small" type="primary" @click.stop="sendComment">发送</el-button>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>
<script lang="ts">
import { Component, Vue, Watch, Ref, Prop } from 'vue-property-decorator';
import uploadList from '@/afterSales/components/uploader/uploadList.vue';
import { uploadQiniu } from '@/utils/upload'
import { commonAction, timeFormat } from '@/utils/common'
import boardItem from './base/boardItem.vue'
// eslint-disable-next-line no-restricted-imports
import { throttle } from 'lodash'
import { CommonModule } from '@/store/modules/common'
@Component({
  name: 'messageBoard',
  components: {
    uploadList,
    boardItem
  }
})
export default class extends Vue {
  [x: string]: any;
  @Prop() public worksheetId!: string;
  @Prop() public id!: string;
  @Prop(Array) public fieldList!: any
  @Prop(Object) public form!: any
  // sendCommentFn直接写成匿名函数，this指向有问题
  private sendComment = throttle(this.sendCommentFn, 1200, { trailing: false })
  private inputVal = '';
  private fileList = [] as any[];
  private ulList = [] as any[];
  private page = {
    pageNumber: 1,
    pageSize: 10
  };

  private totalPage = 0;
  private progress: any = [];
  public getScrollFetchData () {
    this.page.pageNumber += 1;
    this.getFetchData(false);
  }

  private get userObj () {
    return CommonModule.publicCache.userListObj
  }

  public async beforeUpload (file) {
    this.fileName = file.name.replace(/\s/g, '')
    return true
  }

  private uploadError () {
    this.$message({ message: '文件上传失败，请重新选择文件上传', type: 'error' })
  }

  public uploadRequest (request: any) {
    uploadQiniu({ type: 'crm', fileName: this.fileName }, request)
  }

  public onFileProgress ({ percent }, file, fileList) {
    this.progress = this.processList(fileList);
  }

  // 文件上传成功
  public handleSuccess (response, file, fileList) {
    const uploadFile = {
      url: response.domain + '/' + response.key,
      fileName: file.name
    };
    this.fileList.push(uploadFile);
    this.progress = this.processList(fileList);
  }

  private processList (list) {
    console.log(list);
    return list.filter((item) => {
      return item.status !== 'ready' && item.percentage < 100;
    }).map(({ name, percentage }) => {
      return { name, percentage: Math.floor(percentage) };
    });
  }

  public getFetchData (resetList?: any) {
    // resetList是否重置
    if (resetList) {
      this.page.pageNumber = 1;
      this.ulList = [];
      this.$emit('resetScrollTop');
      this.$emit('refreshMoreFlag', true);
      this.$nextTick(() => {
        this.fetchComment();
      });
    } else {
      this.fetchComment();
    }
  }

  private mounted () {
    this.getFetchData(true)
  }

  private async fetchComment () {
    const data = {
      orderId: this.form.id,
      page: {
        pageNumber: this.page.pageNumber,
        pageSize: this.page.pageSize
      }
    };
    commonAction({ url: '/server-work/action/messageBoard/list', method: 'post', data }).then(res => {
      if (res.success) {
        this.totalPage = res.data.page.totalPage;
        const arr = res.data.voList || [];
        if (arr.length === 0) {
          this.$emit('refreshMoreFlag', true);
        } else {
          this.$emit('refreshMoreFlag', false);
        }
        // 如果是第一页
        if (this.page.pageNumber === 1) {
          if (arr.length === 0) {
            this.ulList = [];
          } else {
            this.ulList = arr;
          }
        } else {
          // 如果不是第一页
          this.ulList = [...this.ulList, ...arr];
        }
      }
    })
  }

  private remove (item: any) {
    const index = this.fileList.findIndex((file) => file.url === item.url);
    this.fileList.splice(index, 1);
  }

  private async sendCommentFn () {
    if (!this.inputVal && this.fileList.length === 0) {
      this.$message.error('发送内容不能为空！');
      return false;
    } else {
      const data = {
        orderId: this.form.id,
        content: this.inputVal,
        attach: this.fileList
      };
      commonAction({ url: '/server-work/action/messageBoard/sendMessage', method: 'post', data }).then(res => {
        if (res.success) {
          this.fileList = [];
          this.inputVal = '';
          this.ulList.unshift(res.data);
          this.$emit('resetScrollTop');
        }
      })
    }
  }
}
</script>
<style lang="stylus" scoped>
.empty-text {
	margin-top: 16px
}
.upload--text {
	display: table;
	border: 1px solid #E7E9ED;
	border-radius: 4px;
	height: 32px;
	line-height: 32px;
	padding: 0px 12px;
	margin-right: 10px;
}
.upload--text:hover {
	color: #008CEE;
	border: 1px solid #008CEE;
}
.more-btn {
  cursor: pointer;
	font-size: 12px;
	color: #008bee;
	margin-left: 50px;
	text-align: center;
}
.comment {
	width 100%
	.workSheetCommentBox {
		width 100%
		height 100%
		flex-direction column
		flex 1 1
		display flex
		display -webkit-flex
	}
	.chat-log {
		flex 1 1
		margin-bottom: 120px;
		.activity-panel {
			min-height 0%
			display flex
			flex 1 1 auto
			overflow-x hidden
			overflow-y hidden
			flex-direction column
			.activities-list {
				flex none
				display flex
				flex-direction column
				padding-bottom 24px
			}
		}
	}
}
.send-div {
	position: absolute;
	left: 16px;
	right: 16px;
	bottom: -1px;
	z-index: 10;
	box-sizing: border-box;
	background: #fff;
	.attachments-list {
		margin 0
		position relative
		display flex
		// justify-content space-between
		flex-direction row
		flex-wrap wrap
		.uploader-item {
			height 48px
			position relative
			line-height 20px
			list-style none
			margin 10px 0px 0 0
			background-color #fff
			width 48%
			border-radius 4px
			border 1px solid rgba(230, 230, 230, 1)
			.uploader-wrapper {
				display flex
				justify-content space-between
				padding 8px
				.uploader-handlers {
					justify-content flex-end
					width 30px
					flex-shrink 0
					display flex
					align-items center
				}
				.uploader-content {
					position relative
					overflow hidden
					text-overflow ellipsis
					white-space nowrap
					flex 1 1 auto
					.file-item {
						display flex
						.file-item-content {
							display flex
							min-width 0
							justify-content space-between
							align-items center
							flex 1 1 auto
							.elastic-title {
								display flex
								flex-direction row
								align-items center
								white-space pre
								min-width 0
								.elastic-title-tail {
									flex 0 1 auto
									min-width 0%
									flex-shrink 0
									overflow hidden
								}
								.elastic-title-head {
									text-overflow ellipsis
									flex 0 1 auto
									min-width 0%
									overflow hidden
								}
							}
						}
						.file-item-icon {
							width 32px
							height 32px
							margin-right 8px
						}
					}
				}
			}
		}
	}
	.comment-box-input-wrap {
		padding 4px 0px
	}
	.comment-box-wrap {
		z-index 1
		position relative
		max-height 290px
		overflow auto
		overflow-x hidden
		padding 8px 10px 8px 10px
		transition border 218ms ease 100ms
	}
	.oper-btn {
		display: flex;
    color: #595959;
    padding: 10px 8px 10px 8px;
    justify-content: end;
    align-items: center;
		span {
			cursor pointer
		}
	}
	/deep/.el-textarea__inner {
		width 100%
		border none
		padding 0px
		height 100px
		background-color rgba(0, 0, 0, 0)
		box-sizing border-box
		resize none
	}
}
.image-icon {
	display inline-block
	width 32px
	height 32px
	background-repeat no-repeat
	background-size cover
	background-position 50%
	vertical-align top
	border-radius 4px
}
.activity-creator-wrap {
	background: #fff;
	box-shadow: 0px 0px 12px rgba(170, 191, 205, 0.3);
	border-radius: 10px;
	margin: 0px 0px 16px 0px;
}
</style>
